#include <QtWidgets>

#include "ImageViewerWidget.h"
#include "ViewAdaptor.h"
#include "DocumentAdaptor.h"

#include <cmath>

ImageViewerWidget::ImageViewerWidget(ImageViewAdaptor *view_adaptor, shell::Access_interface & shell_access)
    : _view_adaptor(view_adaptor)
    , _shell_access(shell_access)
    , _image_label(new QLabel(this))
{
    _document_adaptor = dynamic_cast<ImageDocumentAdaptor *>(view_adaptor->document_adaptor().get());
    Q_ASSERT(_document_adaptor);

    _image_label->setBackgroundRole(QPalette::Base);
    _image_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    _image_label->setScaledContents(true);
    _image_label->setFocusPolicy(Qt::StrongFocus);

    setBackgroundRole(QPalette::Dark);
    
    setImage(_document_adaptor->image());
}

void ImageViewerWidget::setImage(QImage &image)
{
    if (image.colorSpace().isValid())
        image.convertToColorSpace(QColorSpace::SRgb);
    _image_label->setPixmap(QPixmap::fromImage(image));
    _scale_factor = 1.0;

    setWidget(_image_label);

    // setVisible(true);

    // if (!fitToWindowAct->isChecked())
        _image_label->adjustSize();
}

void ImageViewerWidget::print(QPrinter * printer)
{
    Q_ASSERT(!_image_label->pixmap(Qt::ReturnByValue).isNull());

    QPainter painter(printer);
    QPixmap pixmap = _image_label->pixmap(Qt::ReturnByValue);
    QRect rect = painter.viewport();
    QSize size = pixmap.size();
    size.scale(rect.size(), Qt::KeepAspectRatio);
    painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
    painter.setWindow(pixmap.rect());
    painter.drawPixmap(0, 0, pixmap);
}

void ImageViewerWidget::copyImage()
{
#ifndef QT_NO_CLIPBOARD
    QGuiApplication::clipboard()->setImage(_document_adaptor->image());
#endif // !QT_NO_CLIPBOARD
}

void ImageViewerWidget::focusInEvent(QFocusEvent * event)
{
    if(event->gotFocus()) {
        _shell_access.displayCursorPosition("");
        _shell_access.displayStatistics("?");
    }
    QScrollArea::focusInEvent(event);
}

void ImageViewerWidget::wheelEvent(QWheelEvent * event)
{
    if (event->modifiers() != Qt::ControlModifier)
        QScrollArea::wheelEvent(event);
}

void ImageViewerWidget::scaleImage(double factor)
{
    if (std::isnan(factor)) {
        _image_label->adjustSize();
        _scale_factor = 1.0;
        return;
    }

    _scale_factor *= factor;
    _image_label->resize(_scale_factor * _image_label->pixmap(Qt::ReturnByValue).size());

    adjustScrollBar(horizontalScrollBar(), factor);
    adjustScrollBar(verticalScrollBar(), factor);
}

void ImageViewerWidget::adjustScrollBar(QScrollBar *scrollBar, double factor)
{
    scrollBar->setValue(int(factor * scrollBar->value()
                            + ((factor - 1) * scrollBar->pageStep()/2)));
}

